/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package projetlif13.model;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author theo
 */
public abstract class Game {

    public static final int TYPE_PVP = 1; //joueur contre joueur
    public static final int TYPE_PVE = 2; // joueur contre ia
    public static final int TYPE_EVE = 3; // ia vs ia
    Player[] players;
    private int currentPlayer;
    protected Board gameBoard;

    public void stop() {
        //stopper le jeu afin que playGame retourne null
        for (int i = 0; i < players.length; i++) {
            if (players[i] instanceof IAPlayer) {
                ((IAPlayer) players[i]).stop();
            }
        }
    }

    public Board getGameBoard() {
        return gameBoard;
    }

    public Game(Player _p1, Player _p2) {
        players = new Player[2];
        players[0] = _p1;
        players[1] = _p2;
        currentPlayer = 0;
    }

    public Player getPlayerById(int id) {
        for (int i = 0; i < players.length; i++) {
            if (players[i].getId() == id) {
                return players[i];
            }
        }
        return null;
    }

    /**
     * Fonction permettant de récupérer le joueur suivant
     *
     * @return retourne le joueur suivant
     */
    private Player nextPlayer() {
        currentPlayer++;
        if (currentPlayer >= players.length) {
            currentPlayer = 0;
        }
        return players[currentPlayer];
    }

    public abstract boolean gameEnded();

    public abstract boolean moveAvailable(Move _m);

    /**
     * Fonction pour savoir si un coup est encore possible
     *
     * @return retourne vrai si il est encore possible de jouer
     */
    public abstract boolean canPlay();

    /**
     * Fonction éxécutant le jeu
     *
     * @return Le joueur ayant gagné la partie
     */
    public Player playGame() {
        Player curPlayer = null;

        while (!gameEnded()) {
            curPlayer = nextPlayer();
            System.out.println("Player turn : " + curPlayer.getId());
            Move m = curPlayer.getMove(gameBoard);
            if (moveAvailable(m)) {
                System.out.println(m.toString());
                gameBoard.makeMove(m, curPlayer);
            } else {
                try {
                    throw new Exception("No move available");
                    //System.exit(1);
                    //System.exit(1);
                } catch (Exception ex) {
                    Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (!canPlay() && !gameEnded()) {
                return null;
            }
        }
        return curPlayer;
    }

    public Player[] getPlayers() {
        return players;
    }
}
